package com.sise.bl.service.impl;

import com.sise.bl.dao.*;
import com.sise.bl.entity.*;
import com.sise.bl.service.AdminService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;
import java.util.Set;

@Transactional
@Service("adminService")
public class AdminServiceImpl implements AdminService {
    @Autowired
    @Qualifier("userDao")
    private UserDao userDao;

    @Autowired
    @Qualifier("typeDao")
    private TypeDao typeDao;

    @Autowired
    @Qualifier("ordersDao")
    private OrdersDao ordersDao;

    @Autowired
    @Qualifier("productDao")
    private ProductDao productDao;

    @Autowired
    @Qualifier("cartDao")
    private CartDao cartDao;

    @Autowired
    @Qualifier("addressDao")
    private AddressDao addressDao;

    @Autowired
    @Qualifier("adminDao")
    private AdminDao adminDao;

    @Override
    public void removeUserById(String id) {
        User user = userDao.selectUserById(Integer.valueOf(id));
        System.out.println(id);
        //清空该用户下的订单
        Set<Orders> orders = user.getOrders();
        if (orders != null) {  //订单存在
            for (Orders order : orders) {
                //删除订单项
                ordersDao.deleteItemByOid(order.getOid());
            }
            ordersDao.deleteOrdersByUid(Integer.valueOf(id));
        }
        if (user.getCarts() != null) {  //购物车存在
            //清空购物车
            cartDao.deleteCartByUid(id);
        }
        if (user.getAddresses() != null) {  //地址存在
            //清空地址
            addressDao.deleteAddressByUid(id);
        }
        adminDao.deleteUserById(user);
    }


    @Override
    public void removeType(String tid) {
        productDao.deleteProductByTid(Integer.valueOf(tid));
        Type type = typeDao.selectTypeByid(Integer.valueOf(tid));

        adminDao.deleteType(type);
    }

    @Override
    public void removeOrderById(String oid) {
        Orders orders = ordersDao.selectOrdersByOid(oid);
        ordersDao.deleteItemByOid(oid);
        ordersDao.deleteOrders(orders);
    }

    @Override
    public void removeProductById(String pid) {
        Product product = productDao.selectProductByPid(Integer.valueOf(pid));
        if (product.getItems() != null) {
            ordersDao.deleteItemByPid(Integer.valueOf(pid));
        }
        productDao.deleteProduct(product);
    }

    @Override
    public int modifyProduct(Product product) {
        int i = productDao.updateProduct(product);
        return i;
    }
}
